package com.ddmmo.exhibition.localBOSS.videoStream.controller;

import com.ddmmo.exhibition.localBOSS.videoStream.service.VideoStreamService;
import io.swagger.annotations.Api;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * <p>
 * 在线播放视频流 - Controller
 * </p>
 *
 * @author JiangYiji
 * @since 2024/09/24
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/videoStream")
@Api(tags = "在线播放视频流 - Controller")
public class VideoStreamController extends Application {

    @Autowired
    private VideoStreamService videoStreamService;

    /**
     * 根据文件路径返回视频流
     */
    @GetMapping("/openVideoForPath")
    public void openVideoForPath(@RequestParam String filePath, HttpServletResponse response, HttpServletRequest request) throws IOException {
        filePath = filePath.replace("\\", "/");
        videoStreamService.openVideoForPath(filePath, response, request);
    }

    /**
     * 视频流 - 全量下载播放
     */
    @GetMapping("/video1")
    public void streamVideo1(HttpServletResponse response) throws IOException {
        // 设置响应的类型为视频流
        response.setContentType("video/mp4");

        File videoFile = new File("C:/Users/JiangYiji/Desktop/213/video1.mp4");
        try (FileInputStream inputStream = new FileInputStream(videoFile);
             OutputStream outputStream = response.getOutputStream()) {

            // 设置响应的长度为视频文件的长度
            response.setContentLength((int) videoFile.length());

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        }
    }

    /**
     * 视频流 - 分段实时播放
     */
    @GetMapping("/video2")
    public void streamVideo(HttpServletResponse response, HttpServletRequest request) throws IOException {
        File videoFile = new File("C:/Users/JiangYiji/Desktop/213/video1.mp4");

        // 设置响应类型为视频流
        response.setContentType("video/mp4");

        // 获取文件长度
        long fileLength = videoFile.length();
        long start = 0;
        long end = fileLength - 1;

        // 处理范围请求
        String range = request.getHeader("Range");
        if (range != null) {
            // 解析范围请求
            String[] ranges = range.replaceAll("bytes=", "").split("-");
            start = Long.parseLong(ranges[0]);
            if (ranges.length > 1) {
                end = Long.parseLong(ranges[1]);
            }

            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
        } else {
            response.setHeader("Accept-Ranges", "bytes");
        }

        // 设置响应的内容长度
        response.setContentLengthLong(end - start + 1);

        try (FileInputStream inputStream = new FileInputStream(videoFile)) {
            inputStream.skip(start);  // 跳过未请求的部分

            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            long bytesToWrite = end - start + 1;
            int bytesRead;

            while (bytesToWrite > 0 && (bytesRead = inputStream.read(buffer, 0, (int) Math.min(buffer.length, bytesToWrite))) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                bytesToWrite -= bytesRead;
            }
            outputStream.flush();
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        // 创建一个媒体对象，指定要播放的视频文件
//        String videoPath = "\\\\LIUCHUAN\\990\\video.mp4";
        String videoPath = "C:/Users/JiangYiji/Desktop/213/video1.mp4";
        // 使用 File 创建一个 URI
        Media media = new Media(new File(videoPath).toURI().toString());

        // 创建一个媒体播放器
        MediaPlayer mediaPlayer = new MediaPlayer(media);

        // 创建一个媒体视图
        MediaView mediaView = new MediaView(mediaPlayer);

        // 创建一个布局，将媒体视图放入其中
        BorderPane root = new BorderPane();
        root.setCenter(mediaView);

        // 创建一个场景，将布局放入其中
        Scene scene = new Scene(root, 800, 600);

        // 设置舞台的场景，并显示舞台
        primaryStage.setScene(scene);
        primaryStage.setTitle("Video Player");
        primaryStage.show();

        // 开始播放视频
        mediaPlayer.play();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
